require 'fileutils'
require 'qiniu'
require 'digest'
require 'openssl'
require 'base64'
require 'time'
class MessageApi < Grape::API
	#通用接口
	version 'v1', using: :path
	format :json
	default_format :json
	formatter :json, Grape::Formatter::Rabl
	resource :message do
		


		# 项目消息
		# 接口编号:2.9.1
		# 参数:
		## user_id    type:String  用户ID
		## page       type: Inte
		# 请求方式: post
		# 返回: 工作ID
		desc '项目消息列表'
    params do
			optional :user_id,    type: String, desc: '用户ID'		
			optional :page,       type: Integer, desc: '页码'
    end
		get 'project_messages' do
			if params[:user_id].nil?
				{code: "400", msg: "缺少用户ID"}
			else
				result = Hash.new
				result["code"] = "0"
				result["msg"] = "OK"
				per_page = 10
				if params[:page].nil? || params[:page] == 1
					messages = Message.where(recipient: params[:user_id], message_type: 2).order(created_at: :desc).limit(per_page)
					message_count = Message.where(recipient: params[:user_id], message_type: 2).order(created_at: :desc).count	
					
					result["messages"] = MessageApi.build_message(messages)
					result["count"] = message_count
					result["previous_page"] = ""
					if message_count > per_page
						result["next_page"] = "2"
					else
						result["next_page"] = ""
					end
					return result
				else
					offset = (params[:page].to_i - 1) * per_page
					messages = Message.where(recipient: params[:user_id], message_type: 2).order(created_at: :desc).limit(per_page).offset(offset)
					message_count = Message.where(recipient: params[:user_id], message_type: 2).order(created_at: :desc).count	
					result["messages"] = MessageApi.build_message(messages)
					result["count"] = message_count
					result["previous_page"] = (params[:page].to_i - 1).to_s
					if message_count > (params[:page].to_i * per_page)
						result["next_page"] = params[:page].to_i + 1
					else
						result["next_page"] = ""
					end
					return result
				end
			end		
		end
		# 系统消息
		# 接口编号:2.9.4
		# 参数:
		## user_id    type:String  用户ID
		## page       type: Inte
		# 请求方式: post
		# 返回: 工作ID
		desc '系统消息'
    params do
			optional :user_id,    type: String, desc: '用户ID'		
			optional :page,       type: Integer, desc: '页码'
    end
		get 'sys_messages' do
			if params[:user_id].nil?
				{code: "400", msg: "缺少用户ID"}
			else
				result = Hash.new
				result["code"] = "0"
				result["msg"] = "OK"
				per_page = 10
				if params[:page].nil? || params[:page] == 1
					messages = Message.where("(recipient = ? AND message_type = 1 AND module_type = 2) or (recipient = ? AND message_type = 1 AND module_type = 1)", params[:user_id], params[:user_id]).order(created_at: :desc).limit(per_page)
					message_count = Message.where("(recipient = ? AND message_type = 1 AND module_type = 2) or (recipient  = ?  AND message_type = 1 AND module_type = 1)", params[:user_id], params[:user_id]).order(created_at: :desc).count
					result["messages"] = MessageApi.build_message(messages)
					result["count"] = message_count
					result["previous_page"] = ""
					if message_count > per_page
						result["next_page"] = "2"
					else
						result["next_page"] = ""
					end
					return result
				else
					offset = (params[:page].to_i - 1) * per_page
					messages = Message.where("(recipient = ? AND message_type = 1 AND module_type = 2) or (recipient = ?  AND message_type = 1 AND module_type = 1)", params[:user_id], params[:user_id]).order(created_at: :desc).limit(per_page).offset(offset)
					message_count = Message.where("(recipient = ? AND message_type = 1 AND module_type = 2) or (recipient = ?  AND message_type = 1 AND module_type = 1)", params[:user_id], params[:user_id]).order(created_at: :desc).count
					result["messages"] = MessageApi.build_message(messages)
					result["previous_page"] = (params[:page].to_i - 1).to_s
					if message_count > (params[:page].to_i * per_page)
						result["next_page"] = params[:page].to_i + 1
					else
						result["next_page"] = ""
					end
					return result
				end
			end		
		end
		# 消息详情
		# 接口编号:2.9.5
		# 参数:
		#  id    type:String  消息ID
		# 请求方式: get
		# 返回: 消息列表
		desc '消息详情'
    params do
			optional :id,    type: String, desc: '用户ID'
			optional :message_type, type: Integer, desc: '消息类型1.系统2项目3置顶'
		end
		get '' do
			if params[:id].nil?
				{code: "400", msg: "缺少消息ID"}
			else
				if params[:message_type].nil?
									message = Message.where(id: params[:id]).first
				if message.nil?
					{code: "400", msg: "消息不存在"}
				else
					if !(message.recipient.nil?)
						message.read_status = 2
						message.save
					end
					
					
					project = Project.where(id: message.project_id).first
					if project.nil?
						{
						code: "0",
						msg: "OK",
						message: {
						id: message.id,
						title: message.title.nil? ? "" : message.title,
						content: message.content,
						message_type: message.message_type,
						module_type: message.module_type.nil? ? -99 : message.module_type,
						module_id: message.module_id.nil? ? -99 : message.module_id,
						project_id: -99, 
						project_name: "", 
						publish_time: message.created_at.strftime("%Y-%m-%d %H:%M"),
						attachment: message.attachment.nil? ? "" : message.attachment,
						read_status: message.read_status,
						confirm_status: message.confirm_status,
						sender_name: message.sender_name,
						unit_name: message.unit_name
						}
					}
					else
						{
						code: "0",
						msg: "OK",
						message: {
						id: message.id,
						title: message.title.nil? ? "" : message.title,
						content: message.content,
						message_type: message.message_type,
						module_type: message.module_type.nil? ? -99 : message.module_type,
						module_id: message.module_id.nil? ? -99 : message.module_id,
						project_id: project.id,
						project_name: project.name,
						publish_time: message.created_at.strftime("%Y-%m-%d %H:%M"),
						attachment: message.attachment.nil? ? "" : message.attachment,
						read_status: message.read_status,
						confirm_status: message.confirm_status,
						sender_name: message.sender_name,
						unit_name: message.unit_name
						}
					}
					end				
				end
				else
					if params[:message_type].to_i == 1 || params[:message_type] == 2
						message = Message.where(id: params[:id]).first
						if message.nil?
							{code: "400", msg: "消息不存在"}
						else
							message.read_status = 2
							message.save
							project = Project.where(id: message.project_id).first
							if project.nil?
								{
								code: "0",
								msg: "OK",
								message: {
								id: message.id,
								title: message.title.nil? ? "" : message.title,
								content: message.content,
								message_type: message.message_type,
								module_type: message.module_type.nil? ? -99 : message.module_type,
								module_id: message.module_id.nil? ? -99 : message.module_id,
								project_id: -99, 
								project_name: "", 
								publish_time: message.created_at.strftime("%Y-%m-%d %H:%M"),
								attachment: message.attachment.nil? ? "" : message.attachment,
								read_status: message.read_status,
								confirm_status: message.confirm_status,
								sender_name: message.sender_name,
								unit_name: message.unit_name
								}
							}
							else
								{
								code: "0",
								msg: "OK",
								message: {
								id: message.id,
								title: message.title.nil? ? "" : message.title,
								content: message.content,
								message_type: message.message_type,
								module_type: message.module_type.nil? ? -99 : message.module_type,
								module_id: message.module_id.nil? ? -99 : message.module_id,
								project_id: project.id,
								project_name: project.name,
								publish_time: message.created_at.strftime("%Y-%m-%d %H:%M"),
								attachment: message.attachment.nil? ? "" : message.attachment,
								read_status: message.read_status,
								confirm_status: message.confirm_status,
								sender_name: message.sender_name,
								unit_name: message.unit_name
								}
							}
							end				
						end
					elsif params[:message_type].to_i ==3
						top_message = TopMessage.where(id: params[:id]).first
						if top_message.nil?
							{code: "400", msg: "消息不存在"}
						else
							{
								code: "0",
								msg: "OK",
								message: {
								id: top_message.id,
								title: top_message.title.nil? ? "" : top_message.title,
								content: top_message.content,
								sender_name: top_message.sender_name,
								unit_name: top_message.unit_name,
								message_type: 3,
								module_type: -99,
								module_id: -99,
								project_id: -99,
								project_name: "",
								publish_time: top_message.created_at.strftime("%Y-%m-%d %H:%M"),
								attachment: "",
								read_status: -99,
								confirm_status: -99
								}
							}
						end
					else
						{code: "400", msg: "消息类型不正确"}
					end
				end

			end		
		end
		# 全部消息
		# 接口编号:2.9.2
		# 参数:
		## user_id    type:String  用户ID
		## page       type: Inte
		# 请求方式: post
		# 返回: 全部消息
		desc '全部消息'
    params do
			optional :user_id,    type: String, desc: '用户ID'
			optional :page,       type: Integer, desc: '页码'
    end
		get 'all_messages' do
			if params[:user_id].nil?
				{code: "400", msg: "缺少用户ID"}
			else
				result = Hash.new
				result["code"] = "0"
				result["msg"] = "OK"
				per_page = 10
				if params[:page].nil? || params[:page] == 1
					messages = Message.where("recipient = ?", params[:user_id]).order(created_at: :desc).limit(per_page)
					message_count = Message.where("recipient = ? ", params[:user_id]).order(created_at: :desc).count			
					result["messages"] = MessageApi.build_message(messages)
					result["count"] = message_count
					result["previous_page"] = ""
					if message_count > per_page
						result["next_page"] = "2"
					else
						result["next_page"] = ""
					end
					return result
				else
					offset = (params[:page].to_i - 1) * per_page
					messages = Message.where("recipient = ?", params[:user_id]).order(created_at: :desc).limit(per_page).offset(offset)
					message_count = Message.where("recipient = ?", params[:user_id]).order(created_at: :desc).count
					result["count"] = message_count
					result["messages"] = MessageApi.build_message(messages)
					result["previous_page"] = (params[:page].to_i - 1).to_s
					if message_count > (params[:page].to_i * per_page)
						result["next_page"] = params[:page].to_i + 1
					else
						result["next_page"] = ""
					end
					return result
				end
			end		
		end

		# 未读消息
		# 接口编号:2.9.3
		# 参数:
		## user_id    type:String  用户ID
		## page       type: Inte
		# 请求方式: post
		# 返回: 未读消息
		desc '未读消息'
    params do
			optional :user_id,    type: String, desc: '用户ID'
			optional :page,       type: Integer, desc: '页码'
    end
		get 'unread_messages' do
			if params[:user_id].nil?
				{code: "400", msg: "缺少用户ID"}
			else
				result = Hash.new
				result["code"] = "0"
				result["msg"] = "OK"
				per_page = 10
				if params[:page].nil? || params[:page] == 1
					messages = Message.where(recipient: params[:user_id], read_status: 1).order(created_at: :desc).limit(per_page)
					message_count = Message.where(recipient: params[:user_id], read_status: 1).order(created_at: :desc).count						
					result["messages"] = MessageApi.build_message(messages)
					result["count"] = message_count
					result["previous_page"] = ""
					if message_count > per_page
						result["next_page"] = "2"
					else
						result["next_page"] = ""
					end
					return result
				else
					offset = (params[:page].to_i - 1) * per_page
					messages = Message.where(recipient: params[:user_id], read_status: 1).order(created_at: :desc).limit(per_page).offset(offset)
					message_count = Message.where(recipient: params[:user_id], read_status: 1).order(created_at: :desc).count
					result["count"] = message_count
					result["messages"] = MessageApi.build_message(messages)
					result["previous_page"] = (params[:page].to_i - 1).to_s
					if message_count > (params[:page].to_i * per_page)
						result["next_page"] = params[:page].to_i + 1
					else
						result["next_page"] = ""
					end
					return result
				end
			end		
		end

		# 首页消息
		# 接口编号:2.9.6
		# 参数:
		## page       type: Inte
		# 请求方式: get
		# 返回: 首页消息
		desc '首页消息'
    params do
    	optional :user_id, type: String, desc: '用户名'
			optional :page,   type: Integer, desc: '页码'
    end
		get 'home_messages' do
			result = Hash.new
			result["code"] = "0"
			result["msg"] = "OK"
			per_page = 10
			if params[:user_id].nil?
				{code: "400", msg: "缺少用户ID"}
			else
				if params[:page].nil? || params[:page] == 1
					top_messages = TopMessage.where(publish_status: 1, message_type: 1).order(created_at: :desc).limit(per_page)
					top_messages_count = TopMessage.where(publish_status: 1, message_type: 1).order(created_at: :desc).count
					if top_messages_count > per_page
						result["messages"] = MessageApi.home_message(top_messages, [])
						result["count"] = per_page
						result["previous_page"] = ""
						result["next_page"] = "2"
					elsif top_messages_count == per_page
						result["messages"] = MessageApi.home_message(top_messages, [])
						result["count"] = per_page
						result["previous_page"] = ""
						result["next_page"] = ""
					else
							other_per_page = per_page - top_messages_count
							messages=  Message.where("(message_type = 1 AND recipient = ?) OR (message_type = 2 AND recipient = ? ) ", params[:user_id], params[:user_id]).order(created_at: :desc).limit(other_per_page)
							messages_count =  Message.where("(message_type = 1 AND recipient = ?) OR (message_type = 2 AND recipient = ? ) ", params[:user_id], params[:user_id]).order(created_at: :desc).count
							result["messages"] = MessageApi.home_message(top_messages, messages)
							result["count"] = top_messages_count + messages.count
							result["previous_page"] = ""
							if messages_count > other_per_page
								result["next_page"] = "2"
							elsif messages_count == other_per_page
								result["next_page"] = ""
							else	
								result["next_page"] = ""
							end
					end
					return result
				else
					offset = (params[:page].to_i - 1) * per_page
					top_messages = TopMessage.where(publish_status: 1, message_type: 1).order(created_at: :desc).limit(per_page).offset(offset)
					top_messages_count = TopMessage.where(publish_status: 1, message_type: 1).order(created_at: :desc).offset(offset).count
					top_messages_all_count = TopMessage.where(publish_status: 1, message_type: 1).order(created_at: :desc).count
					if top_messages_count > per_page
						result["messages"] = MessageApi.home_message(top_messages, [])
						result["count"] = per_page
						result["previous_page"] = params[:page].to_i - 1
						result["next_page"] = params[:page].to_i + 1
					elsif top_messages_count == per_page
						result["messages"] = MessageApi.home_message(top_messages, [])
						result["count"] = per_page
						result["previous_page"] = params[:page].to_i - 1
						result["next_page"] = ""
					else
						per_page = per_page - top_messages_count
						offset =  (params[:page].to_i - 1) * per_page - top_messages_all_count
						messages=  Message.where("(message_type = 1 AND recipient = ?) OR (message_type = 2 AND recipient = ? ) ", params[:user_id], params[:user_id]).order(created_at: :desc).limit(per_page).offset(offset)
						messages_count =  Message.where("(message_type = 1 AND recipient = ?) OR (message_type = 2 AND recipient = ? ) ", params[:user_id], params[:user_id]).order(created_at: :desc).offset(offset).count
						result["messages"] = MessageApi.home_message(top_messages, messages)
						result["count"] = top_messages_count + messages.count
						result["previous_page"] = params[:page].to_i - 1
						if messages_count > per_page
							result["next_page"] = params[:page].to_i + 1
						else
							result["next_page"] = ""
						end
					end
					return result
				end
			end
		end

		# 消息确认
		# 接口编号:2.9.7
		# 参数:
		## page       type: Inte
		# 请求方式: post
		# 返回: 是否确认
		desc '消息确认'
    params do
    	optional :user_id, type: String, desc: '用户ID'
			optional :message_id,   type: String, desc: '消息ID'
    end
		post 'message_confirm' do
			if params[:user_id].nil?
				{code: "400", msg: "缺少用户ID"}
			elsif params[:message_id].nil?
				{code: "400", msg: "缺少消息ID"}
			else
				message = Message.where(id: params[:message_id], module_type: 2, confirm_status: 1, recipient: params[:user_id]).first
				if message.nil?
					{code: "400", msg: "消息不可确认或已确认"}
				else
					message.confirm_status = 2
					if message.save
						{code: "0", msg: "OK"}
					else
						{code: "400", msg: "消息确认失败"}
					end
				end
			end		
		end

		##########新增消息接口
		### user_id
		### message_type //消息类别  1.系统消息 2.项目消息
		### module_type  //消息类型  1.加入项目, 2.离开项目, 3.工作安排, 4.工作申请, 5.工作评价, 6.项目公告
		### module_id    //对应的类型id,如果module_type是1或者2，则module_id是project_id,如果module_type是3或者4，则module_id是工作ID
		### content		   消息内容
		def self.new_message(user_id, message_type, module_type, module_id, project_id, title, content)
			message = Message.new
			message.recipient = user_id
			message.message_type = message_type
			message.module_type = module_type
			message.module_id = module_id
			message.title = title
			message.content = content
			message.read_status = 1
			message.project_id = project_id
			message.save
		end
		##########新增消息接口(new)
		### 增加了发布人和发布单位两个字段
		### user_id
		### message_type //消息类别  1.系统消息 2.项目消息
		### module_type  //消息类型  1.加入项目, 2.离开项目, 3.工作安排, 4.工作申请, 5.工作评价, 6.项目公告
		### module_id    //对应的类型id,如果module_type是1或者2，则module_id是project_id,如果module_type是3或者4，则module_id是工作ID
		### content		   消息内容
		### sen
		def self.new_message2(user_id, message_type, module_type, module_id, project_id, title, content,unit_name,sender_name)
			message = Message.new
			message.recipient = user_id
			message.message_type = message_type
			message.module_type = module_type
			message.module_id = module_id
			message.title = title
			message.content = content
			message.read_status = 1
			message.project_id = project_id
			message.unit_name= unit_name
			message.sender_name = sender_name
			message.save
		end

		###########消息模板生成器
		def self.build_message(messages)
			message_list = []
			messages.each do |m|
				if m.project_id.nil?
					message = Hash.new
					message["id"] = m.id
					message["title"] = m.title.nil? ? "" : m.title
					message["content"] = m.content
					message["message_type"] = m.message_type
					message["module_type"] = m.module_type.nil? ? -99 : m.module_type
					message["module_id"] = -99
					message["project_id"] = -99
					message["project_name"] = ""
					message["publish_time"] = m.created_at.strftime("%Y-%m-%d %H:%M")
					message["attachment"] = m.attachment.nil? ? "" : m.attachment
					message["read_status"] = m.read_status
					message["confirm_status"] = -99
					message["unit_name"] = m.unit_name
					message["sender_name"]= m.sender_name
					message_list << message
				else
					message = Hash.new
					project = Project.where(id: m.project_id).first
					message["id"] = m.id
					message["title"] = m.title.nil? ? "" : m.title
					message["content"] = m.content
					message["message_type"] = m.message_type
					message["module_type"] = m.module_type.nil? ? -99 : m.module_type
					message["module_id"] = m.module_id
					message["project_id"] = m.project_id
					message["project_name"] = project.name
					message["publish_time"] = m.created_at.strftime("%Y-%m-%d %H:%M")
					message["attachment"] = m.attachment.nil? ? "" : m.attachment
					message["read_status"] = m.read_status
					message["confirm_status"] = m.confirm_status
					message["unit_name"] = m.unit_name
					message["sender_name"]= m.sender_name
					message_list << message
				end
			end
			return message_list
		end

		###########消息模板生成器
		def self.home_message(top_messages, other_messages)
			message_list = []
			top_messages.each do |tm|
					message = Hash.new
					message["id"] = tm.id
					message["title"] = tm.title.nil? ? "" : tm.title
					message["content"] = tm.content
					message["message_type"] = 3
					message["module_type"] = -99
					message["module_id"] = -99
					message["project_id"] = -99
					message["project_name"] = ""
					message["publish_time"] = tm.created_at.strftime("%Y-%m-%d %H:%M")
					message["attachment"] = ""
					message["read_status"] = 1
					message["confirm_status"] = -99
					message["unit_name"] = tm.unit_name
					message["sender_name"]= tm.sender_name
					message_list << message
			end
			other_messages.each do |m|
				if m.project_id.nil?
					message = Hash.new
					message["id"] = m.id
					message["title"] = m.title.nil? ? "" : m.title
					message["content"] = m.content
					message["message_type"] = m.message_type
					message["module_type"] = m.module_type.nil? ? -99 : m.module_type
					message["module_id"] = -99
					message["project_id"] = -99
					message["project_name"] = ""
					message["publish_time"] = m.created_at.strftime("%Y-%m-%d %H:%M")
					message["attachment"] = m.attachment.nil? ? "" : m.attachment
					message["read_status"] = m.read_status
					message["confirm_status"] = -99
					message["unit_name"] = m.unit_name
					message["sender_name"]= m.sender_name
					message_list << message
				else
					message = Hash.new
					project = Project.where(id: m.project_id).first
					message["id"] = m.id
					message["title"] = m.title.nil? ? "" : m.title
					message["content"] = m.content
					message["message_type"] = m.message_type
					message["module_type"] = m.module_type.nil? ? -99 : m.module_type
					message["module_id"] = m.module_id
					message["project_id"] = m.project_id
					message["project_name"] = project.name
					message["publish_time"] = m.created_at.strftime("%Y-%m-%d %H:%M")
					message["attachment"] = m.attachment.nil? ? "" : m.attachment
					message["read_status"] = m.read_status
					message["confirm_status"] = m.confirm_status
					message["unit_name"] = m.unit_name
					message["sender_name"]= m.sender_name
					message_list << message
				end
			end
			return message_list
		end


		def self.build_top_message(messages)
			message_list = []
			messages.each do |m|
				message = Hash.new
				message["id"] = m.id
				message["title"] = m.title.nil? ? "" : m.title
				message["content"] = m.content
				message["publish_time"] = m.created_at.strftime("%Y-%m-%d %H:%M")
				message["unit_name"] = m.unit_name
				message["sender_name"]= m.sender_name
				message_list << message
			end
			return message_list
		end

		def self.build_admin_message(messages)
			message_list = []
			messages.each do |m|
				message = Hash.new
				message["id"] = m.id
				message["title"] = m.title.nil? ? "" : m.title
				message["content"] = m.content
				message["publish_time"] = m.created_at.strftime("%Y-%m-%d %H:%M")
				message["unit_name"] = m.unit_name
				message["sender_name"]= m.sender_name
				message_list << message
			end
			return message_list
		end
	end
end
